﻿using SD.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using NLog;

namespace SD.Controllers
{
    [RoutePrefix("Film")]
    public class FilmController : Controller
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        private SD.EF.SdContext db = new EF.SdContext();

        [Route]
        public ActionResult Index() {
            return Redirect("/");
        }

        //GET: Film/Recommendations
        [Route("Recommendations")]
        public ActionResult Recommendations()
        {
            var watchList = db
                .Films
                .Where(x => x.Recommended)
                .Select(x => new FilmViewModel
                {
                    Id = x.Id,
                    Altersfreigabe = x.Altersfreigabe,
                    BigImg = x.BigImg,
                    SmallImg = x.SmallImg,
                    Darsteller = x.Darsteller,
                    DeName = x.DeName,
                    EnName = x.EnName,
                    Inhalt = x.Inhalt,
                    KeyName = x.KeyName,
                    Laufzeit = x.Laufzeit,
                    Regisseur = x.Regisseur,
                    Verleihrechte = x.Verleihrechte
                }).ToList();

            return View(watchList);
        }

        //GET: Film/News
        [Route("News")]
        public ActionResult News()
        {
            var watchList = db
                .Films
                .Where(x => x.New)
                .Select(x => new FilmViewModel
                {
                    Id = x.Id,
                    Altersfreigabe = x.Altersfreigabe,
                    BigImg = x.BigImg,
                    SmallImg = x.SmallImg,
                    Darsteller = x.Darsteller,
                    DeName = x.DeName,
                    EnName = x.EnName,
                    Inhalt = x.Inhalt,
                    KeyName = x.KeyName,
                    Laufzeit = x.Laufzeit,
                    Regisseur = x.Regisseur,
                    Verleihrechte = x.Verleihrechte
                }).ToList();

            return View(watchList);
        }

        //GET: Film/MostViewed
        [Route("MostViewed")]
        public ActionResult MostViewed()
        {
            var watchList = db
                .Films
                .Where(x => x.MostViewed)
                .Select(x => new FilmViewModel
                {
                    Id = x.Id,
                    Altersfreigabe = x.Altersfreigabe,
                    BigImg = x.BigImg,
                    SmallImg = x.SmallImg,
                    Darsteller = x.Darsteller,
                    DeName = x.DeName,
                    EnName = x.EnName,
                    Inhalt = x.Inhalt,
                    KeyName = x.KeyName,
                    Laufzeit = x.Laufzeit,
                    Regisseur = x.Regisseur,
                    Verleihrechte = x.Verleihrechte
                }).ToList();

            return View(watchList);
        }

        //GET: Film/Specials
        [Route("Specials")]
        public ActionResult Specials()
        {
            var watchList = db
                .Films
                .Where(x => x.Specials)
                .Select(x => new FilmViewModel
                {
                    Id = x.Id,
                    Altersfreigabe = x.Altersfreigabe,
                    BigImg = x.BigImg,
                    SmallImg = x.SmallImg,
                    Darsteller = x.Darsteller,
                    DeName = x.DeName,
                    EnName = x.EnName,
                    Inhalt = x.Inhalt,
                    KeyName = x.KeyName,
                    Laufzeit = x.Laufzeit,
                    Regisseur = x.Regisseur,
                    Verleihrechte = x.Verleihrechte
                }).ToList();

            return View(watchList);
        }

        // Film/Orga
        [Route("{key}")]
        public ActionResult Show(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                return Redirect("/");

            var film = db.Films.FirstOrDefault(x => x.KeyName == key);

            if (film == null)
                return Redirect("/");

            FilmViewModel model = new FilmViewModel
            {
                Id = film.Id,
                KeyName = film.KeyName,
                BigImg = film.BigImg,
                SmallImg = film.SmallImg,
                EnName = film.EnName,
                DeName = film.DeName,
                Regisseur = film.Regisseur,
                Darsteller = film.Darsteller,
                Laufzeit = film.Laufzeit,
                Altersfreigabe = film.Altersfreigabe,
                Verleihrechte = film.Verleihrechte,
                Inhalt = film.Inhalt,
            };

            if (!User.Identity.IsAuthenticated)
            {
                 return View(model);
            }
            else
            {

                Guid userId;
                Guid.TryParse(User.Identity.GetUserId(), out userId);

                var orderId = Guid.NewGuid().ToString().Substring(0, 20);

                db.Orders.Add(new EF.OrderEntity
                {
                    Id = orderId,
                    FilmId = film.Id,
                    UserId = userId,
                    Timestamp = DateTime.Now
                });

                db.SaveChanges();

                var aid = "28101";
                var amount = "1";
                var clearingtype = "cc";
                var currency = "EUR";
                var de = "Park";
                var id = "1";
                var mode = "test";
                var no = "1";
                var portalId = "2019810";
                var pr = "1";
                var reference = orderId.ToString();
                var request = "authorization";
                //var successurl = "http://s18093859.onlinehome-server.info/me/BuyingsList";

                var va = "1";


                var customerId = "26994";

                string text = aid + amount + clearingtype +
                    currency + de + id + mode + no + portalId + pr + reference + request
                    //+ successurl 
                    + va + "a2cliM15v3K9zkGi";
                string hashStr = "";

                byte[] hash;
                using (MD5 md5 = MD5.Create())
                {
                    hash = md5.ComputeHash(Encoding.Default.GetBytes(text));
                    hashStr = System.BitConverter.ToString(hash).ToLowerInvariant();
                    hashStr = hashStr.Replace("-", string.Empty);
                }

                model.aid = aid;
                model.amount = amount;
                model.clearingtype = clearingtype;
                model.currency = currency;
                model.De = de;
                model.Idm = id;
                model.mode = mode;
                model.No = no;
                model.portalid = portalId;
                model.Pr = pr;
                model.reference = reference;
                model.request = request;
                model.Va = va;
                model.hash = hashStr;

                return View(model);
            }
        }

        [Route("Status")]
        public void Status(PayOneTransaction transaction)
        {
            logger.Debug("Status");

            var order = db.Orders.FirstOrDefault(x => x.Id == transaction.reference);
            if (order == null)
            {
                logger.Error("Transcation with Id {0} is not in DB", transaction.reference);
            }
            else
            {
                db.Buyings.Add(new EF.BuyingEntity() { Id = Guid.NewGuid(), FilmId = order.FilmId, UserId = order.UserId, Timestamp = DateTime.Now });
                db.SaveChanges();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}